from fastapi import Request, Response
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.types import ASGIApp
import logging
from ..services.user_service import UserService
from ..config.settings import settings

logger = logging.getLogger(__name__)

class AutoRefreshMiddleware(BaseHTTPMiddleware):
    """JWT自动刷新中间件"""
    
    def __init__(self, app: ASGIApp):
        super().__init__(app)
        self.user_service = UserService()
    
    async def dispatch(self, request: Request, call_next):
        response = await call_next(request)
        
        # 只处理成功的API请求
        if (response.status_code == 200 and 
            request.url.path.startswith("/api/") and
            "authorization" in request.headers):
            
            try:
                # 提取令牌
                auth_header = request.headers.get("authorization", "")
                if auth_header.startswith("Bearer "):
                    token = auth_header[7:]
                    
                    # 检查令牌过期信息
                    token_info = self.user_service.get_token_expiry_info(token)
                    if token_info and token_info.get("should_refresh", False):
                        # 添加刷新提示头
                        response.headers["X-Token-Refresh-Required"] = "true"
                        response.headers["X-Token-Remaining-Seconds"] = str(
                            int(token_info.get("remaining_seconds", 0))
                        )
                        
            except Exception as e:
                logger.debug(f"自动刷新检查失败: {str(e)}")
        
        return response